<template>
  <div class="assets-management">
    <div class="page-header">
      <h2>资产管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="资产摘要">
          <el-input v-model="searchForm.assetsAbstract" placeholder="请输入资产摘要" clearable />
        </el-form-item>
        <el-form-item label="收支类型">
          <el-select v-model="searchForm.incomeType" placeholder="请选择收支类型" clearable>
            <el-option label="收入" :value="1" />
            <el-option label="支出" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="账单类型">
          <el-select v-model="searchForm.assetsType" placeholder="请选择账单类型" clearable>
            <el-option label="订单收入" :value="1" />
            <el-option label="订单支出" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchAssets">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增资产
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="assetsList" v-loading="loading" stripe>
        <el-table-column prop="assetsId" label="资产ID" width="80" />
        <el-table-column prop="incomeType" label="收支类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.incomeType === 1 ? 'success' : 'danger'">
              {{ getIncomeTypeText(row.incomeType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assetsBalance" label="资产余额" width="120">
          <template #default="{ row }">
            <span :style="{ color: row.incomeType === 1 ? '#67c23a' : '#f56c6c' }">
              ¥{{ row.assetsBalance?.toFixed(2) || '0.00' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="assetsPrice" label="资产价格" width="120">
          <template #default="{ row }">
            <span :style="{ color: row.incomeType === 1 ? '#67c23a' : '#f56c6c' }">
              {{ row.incomeType === 1 ? '+' : '-' }}¥{{ row.assetsPrice?.toFixed(2) || '0.00' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="assetsType" label="账单类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.assetsType === 1 ? 'success' : 'warning'">
              {{ getAssetsTypeText(row.assetsType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assetsAbstract" label="资产摘要" width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editAssets(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteAssets(row.assetsId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑资产' : '新增资产'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="assetsForm" :rules="assetsRules" ref="assetsFormRef" label-width="100px">
        <el-form-item label="收支类型" prop="incomeType">
          <el-select v-model="assetsForm.incomeType" placeholder="请选择收支类型">
            <el-option label="收入" :value="1" />
            <el-option label="支出" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="资产余额" prop="assetsBalance">
          <el-input v-model="assetsForm.assetsBalance" placeholder="请输入资产余额" />
        </el-form-item>
        <el-form-item label="资产价格" prop="assetsPrice">
          <el-input v-model="assetsForm.assetsPrice" placeholder="请输入资产价格" />
        </el-form-item>
        <el-form-item label="账单类型" prop="assetsType">
          <el-select v-model="assetsForm.assetsType" placeholder="请选择账单类型">
            <el-option label="订单收入" :value="1" />
            <el-option label="订单支出" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="资产摘要" prop="assetsAbstract">
          <el-input v-model="assetsForm.assetsAbstract" type="textarea" placeholder="请输入资产摘要" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { assetsApi } from '@/api/assets'

// 响应式数据
const loading = ref(false)
const assetsList = ref([])
const allAssetsList = ref([]) // 存储所有数据用于客户端分页
const showAddDialog = ref(false)
const isEdit = ref(false)
const assetsFormRef = ref()

// 搜索表单
const searchForm = reactive({
  assetsAbstract: '',
  incomeType: null,
  assetsType: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 资产表单
const assetsForm = reactive({
  assetsId: null,
  incomeType: null,
  assetsBalance: '',
  assetsPrice: '',
  assetsType: null,
  assetsAbstract: ''
})

// 表单验证规则
const assetsRules = {
  incomeType: [
    { required: true, message: '请选择收入类型', trigger: 'change' }
  ],
  assetsBalance: [
    { required: true, message: '请输入资产余额', trigger: 'blur' }
  ],
  assetsPrice: [
    { required: true, message: '请输入资产价格', trigger: 'blur' }
  ],
  assetsType: [
    { required: true, message: '请选择资产类型', trigger: 'change' }
  ],
  assetsAbstract: [
    { required: true, message: '请输入资产摘要', trigger: 'blur' }
  ]
}

// 获取收支类型文本
const getIncomeTypeText = (type) => {
  const typeMap = {
    1: '收入',
    0: '支出'
  }
  return typeMap[type] || '未知'
}

// 获取账单类型文本
const getAssetsTypeText = (type) => {
  const typeMap = {
    1: '订单收入',
    0: '订单支出'
  }
  return typeMap[type] || '未知'
}

// 搜索资产
const searchAssets = async () => {
  loading.value = true
  try {
    const response = await assetsApi.getAssetsList(searchForm)
    if (response.code === 200) {
      allAssetsList.value = response.data || []
      updateDisplayedData()
    }
  } catch (error) {
    console.error('搜索资产失败:', error)
    ElMessage.error('获取资产列表失败')
  } finally {
    loading.value = false
  }
}

// 更新显示的数据（客户端分页）
const updateDisplayedData = () => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  assetsList.value = allAssetsList.value.slice(start, end)
  pagination.total = allAssetsList.value.length
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    assetsAbstract: '',
    incomeType: null,
    assetsType: null
  })
  searchAssets()
}

// 编辑资产
const editAssets = (row) => {
  isEdit.value = true
  Object.assign(assetsForm, row)
  showAddDialog.value = true
}

// 删除资产
const deleteAssets = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个资产吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await assetsApi.deleteAssets(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchAssets()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除资产失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await assetsFormRef.value.validate()

    const response = isEdit.value
      ? await assetsApi.updateAssets(assetsForm)
      : await assetsApi.addAssets(assetsForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchAssets()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(assetsForm, {
    assetsId: null,
    incomeType: null,
    assetsBalance: '',
    assetsPrice: '',
    assetsType: null,
    assetsAbstract: ''
  })
  isEdit.value = false
  assetsFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1 // 重置到第一页
  updateDisplayedData()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  updateDisplayedData()
}

// 初始化
onMounted(() => {
  searchAssets()
})
</script>

<style scoped>
.assets-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>